import fs from "fs-extra";
import chalk from "chalk";
import path from "path";
import { fileURLToPath } from 'url';
import logSymbols from 'log-symbols'

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath);

// 获取当前path
export function getDirPath (fileName) {
  // 获取当前文件的路径
  const __filename = fileURLToPath(import.meta.url);
  // 获取当前文件所在的目录
  const __dirname = path.dirname(__filename);
  return path.join(__dirname, fileName);
}

// 删除文件夹
export async function removeDir(dir) {
  try {
    await fs.remove(resolveApp(dir));
    console.log(logSymbols.warning, `已覆盖同名文件夹${dir}`);
  } catch (err) {
    console.log(err);
  }
}

export async function clone (dir, name) {
  try {
    await fs.copySync(dir, name)
  } catch (err) {
    console.log(err);
    console.log(logSymbols.warning, chalk.yellow("复制模板失败"));
  }
}

// 修改package.json配置
export async function changePackageJson(name, template, info) {
  try {
    const path = getDirPath('template') + '/' + template
    await clone(path, name)
    const pkg = await fs.readJson(resolveApp(`${name}/package.json`));
    pkg.name = name
    Object.keys(info).forEach((item) => {
      if (info[item] && info[item].trim()) {
        pkg[item] = info[item];
      }
    });
    await fs.writeJson(resolveApp(`${name}/package.json`), pkg, { spaces: 2 });
  } catch (err) {
    console.log(err);
    console.log(logSymbols.warning, chalk.yellow("更新项目信息失败,请手动修改package.json"));
  }
}
